<template>
  <el-card v-if="store.getters.loggedUser" style="width: 50%">
    <h1>发表帖子</h1>
    <el-form ref="postRef" status-icon :rules="rules" :model="post">
      <el-form-item prop="title">
        <div class="item">
          <el-icon class="icon" size="30px">
            <icon-mdi-message-processing-outline />
          </el-icon>
          <el-input placeholder="帖子标题" v-model="post.title" />
        </div>
      </el-form-item>
      <el-form-item prop="tagId">
        <div class="item">
          <el-icon class="icon" size="30px">
            <icon-mdi-message-processing-outline />
          </el-icon>
          <el-select v-model="post.tagId" clearable placeholder="选个 tag">
            <el-option
              v-for="item in tags"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
      </el-form-item>
      <el-form-item prop="content">
        <div class="item">
          <el-icon class="icon" size="30px">
            <icon-mdi-message-processing-outline />
          </el-icon>
          <x-edit ref="xEditRef"></x-edit>
        </div>
      </el-form-item>
    </el-form>
    <div class="submit">
      <el-button type="primary" @click="handleSubmit(postRef)">提交</el-button>
    </div>
  </el-card>
</template>

<script setup>
import { publishPost, getTags } from "@/api/postAPI";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

const store = useStore();
const post = reactive({
  title: "",
  content: "",
  tagId: "",
});
const tags = ref();
const postRef = ref();
const xEditRef = ref();
const router = useRouter();
const rules = reactive({
  title: [{ required: true, message: "请输入帖子标题", trigger: "blur" }],
  tagId: [{ required: true, message: "请输入帖子 tag", trigger: "blur" }],
});

const handleSubmit = async (formEl) => {
  // 手动给 post.content 赋值
  post.content = xEditRef.value.getHtml();
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if ((xEditRef.value.getText() || "").trim() == "") {
        ElMessage.error("请输入帖子内容, 至少打几个字好吧");
      } else {
        publishPost(post).then((data) => {
          ElMessage.success(data.message);
          router.push("/");
        });
      }
    }
  });
};
getTags().then((data) => {
  tags.value = data.data;
});
</script>

<style scoped>
.item {
  display: flex;
  width: 100%;
}

.icon {
  margin-right: 10px;
}

.submit {
  display: flex;
  justify-content: end;
}
</style>
